package com.hcj.admin.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hcj.admin.entity.TUser;
import com.hcj.admin.service.ITUserService;
import com.hcj.util.commonUtil.BaseUtil;
import com.hcj.util.excelReport.ExcelReport;
import com.hcj.util.resultUtil.Json;
import com.hcj.util.resultUtil.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author HuangChangjin
 * @since 2017-10-23
 */
@RestController
@RequestMapping("/front")
public class TUserController {
    private static  final Logger logger = LoggerFactory.getLogger(TUserController.class);
    @Autowired
    private ITUserService userService;

    @GetMapping("list")
    public Object list(){
        //return  userService.selectList(new EntityWrapper<TUser>());
        return  userService.getByUserName("admin");
    }

    // ********** CRUD *************************** Start

    @PostMapping("/")
    public Json add(TUser user){
        if (!BaseUtil.isEmpty(user.getUserName())){
            return JsonResult.json("用户名不能为空");
        }
        logger.info("add接收到的参数========》\n{}",user);
        Boolean result = true;//userService.insert(user);
        if (result){
            return JsonResult.jsonSuccess("添加成功",user);
        }else {
            return JsonResult.json("添加失败");
        }
    }

    @PutMapping("/")
    public Json edit(TUser user){
        if (!BaseUtil.isEmpty(user.getId())){
            return JsonResult.json("ID不能为空");
        }
        if (!BaseUtil.isEmpty(user.getUserName())){
            return JsonResult.json("用户名不能为空");
        }
        logger.info("edit接收到的参数========》\n{}",user);
        Boolean result = true;// userService.updateById(user);
        if (result){
            return JsonResult.jsonSuccess("编辑成功",user);
        }else {
            return JsonResult.json("编辑失败");
        }
    }
    //@RequestMapping(path = "/{id}", method = RequestMethod.DELETE)
    @DeleteMapping("/")
    public Json delete(Integer id){
        logger.info("delete接收到的参数========》\n{}",id);
        Boolean result = true;// userService.deleteById(id);
        if (result){
            return JsonResult.jsonSuccess("删除成功");
        }else {
            return JsonResult.json("删除失败");
        }
    }

    @GetMapping("/")
    public Json get(Integer id){
        TUser user = userService.selectById(id);
        return JsonResult.jsonSuccess("查询成功",user);
    }
    // ****************** CRUD ***********************
    // TODO 常用功能 ： 1.文件上传

    @PostMapping("/upload")
    public Json upload(@RequestParam(value = "file", required = true) MultipartFile file, HttpServletRequest request){
        logger.info("\n request.getContextPath()====>{}",request.getContextPath());
        logger.info("\n request.getRequestURL()====>{}",request.getRequestURL());
        logger.info("\n request.getSession().getServletContext().getRealPath(\"/\")====>{}",request.getSession().getServletContext().getRealPath("/"));
        BufferedOutputStream stream = null;
        byte[] bytes = new byte[0];
        String saveFileName = file.getOriginalFilename();
        String savePath = request.getContextPath();
        String path = savePath + saveFileName;
        logger.info("\n文件保存的路径={}",path);
        try {
            File saveFile = new File(path);
            if (!saveFile.exists()){
                saveFile.createNewFile();
            }
            // 方法1：以流的形式写入新文件
            bytes = file.getBytes();
            stream = new BufferedOutputStream(new FileOutputStream(saveFile));
            stream.write(bytes);
            stream.close();
            // 方法2：以拷贝的形式
            FileCopyUtils.copy(file.getBytes(),new File(savePath + "new" + saveFileName));
            return JsonResult.jsonSuccess("上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return JsonResult.json("上传失败");
        }
    }

    @GetMapping("/download")
    public void download(@RequestParam(value = "path", required = false) String fileRealPath, HttpServletRequest request, HttpServletResponse response){
        logger.info("\n  request.getContextPath()====>{}",request.getContextPath());
        logger.info("\n  request.getRequestURL()====>{}",request.getRequestURL());
        logger.info("\n  request.getSession().getServletContext().getRealPath(\"/\")====>{}",request.getSession().getServletContext().getRealPath("/"));
        // 头部信息
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        //response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        BufferedInputStream  inputStream = null;
        byte[] buff = new byte[1024];
        logger.info("\n 文件请求的路径={}",fileRealPath);
        // 测试用
        fileRealPath = "F:/workspace/mybatisplus-spring-boot/src/main/resources/db/shiro.txt";
        try {
            // step1: 检测文件是否存在
            File file = new File(fileRealPath);
            if (!file.exists()){
                //return JsonResult.json("文件不存在，下载失败");
                file.createNewFile();
                return;
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
            // step2: 输入流
            inputStream = new BufferedInputStream(new FileInputStream(file));
            int i = inputStream.read(buff);
            // step3: 拿到输出流
            OutputStream os = response.getOutputStream();
            // step4: 输出到客户端
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = inputStream.read(buff);
            }
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
            //return JsonResult.json("下载失败");
            return;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    //return JsonResult.json("下载失败");
                    return;
                }
            }
        }
        //return JsonResult.jsonSuccess("下载成功");
    }

    // TODO 2.EXCEL导入导出【报表的生成】

    @RequestMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException {
        // 数据准备【long类型的要转成string,否则在excel中会丢失精度】
        List<TUser> dataList =  userService.selectList(new EntityWrapper<TUser>());
        Map<String, Object> beans = new HashMap<>();
        beans.put("list", dataList);
        // 填充报表
        String templateFileName = "F:/workspace/mybatisplus-spring-boot/src/main/resources/excelTemplate/userExportTemplate.xls";
        File file = new File(templateFileName);
        if (!file.exists()){
            logger.error("模板文件不存在===>\n",templateFileName);
            //file.createNewFile();
            return;
        }
        InputStream inputStream = new ExcelReport().makeReportFromTemplet(templateFileName, beans);
        // 头部信息
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        byte[] buff = new byte[1024];
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + "exportExcel.xls");
            int i = inputStream.read(buff);
            // step3: 拿到输出流
            OutputStream os = response.getOutputStream();
            // step4: 输出到客户端
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = inputStream.read(buff);
            }
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }


	
}
